<template>
    <a-select v-model:value="selected" show-search mode="multiple" placeholder="请选择角色" :fieldNames="{label:'displayName',value:'id'}"
        :options="dataSource" :filter-option="filterOption" @change="handleChange" :loading="loading"
        style="width: 100%" />
</template>
<script setup lang="ts">
import { RoleApi } from '@/api/services';
import { RoleDto } from '@/api/services/types';
import { message } from 'ant-design-vue';
import { onMounted, ref, watch } from 'vue';

const props = defineProps({
    value: {
        type: Array,
        default: () => {
            return []
        }
    },
})
const emits = defineEmits(['update:value', 'change'])

const selected = ref<Array<string>>([])
const loading = ref(false)


const dataSource = ref<Array<RoleDto>>([])

const filterOption = (input: string, option: RoleDto) => {
    return option.displayName.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const loadData = function () {
    loading.value = true
    RoleApi.getAll().then(res => {
        const { code, data, msg } = res;
        if (code == 0) {
            dataSource.value = data.items || [];
        } else {
            message.error(msg);
        }

    }).finally(() => {
        loading.value = false
    })
}

const handleChange = function (val: Array<string>) {
    val = val || [];
    emits('update:value', val);
    emits('change', val)
}

onMounted(() => {
    loadData();
})


watch(() => props.value, (val) => {
    selected.value = val as Array<string> || [];
}, { immediate: true })

</script>